<template>
  <div class="companyManage">
    <!-- 列表页 -->
    <div v-if="!isAdd&&!isView">
      <div class="search">
        <el-form :inline="true" :model="companyManage" class="demo-form-inline companyAdd">
          <el-form-item label="单位名称">
            <el-input v-model="companyManage.companyName" placeholder="单位名称"></el-input>
          </el-form-item>
          <el-form-item label="单位类型">
            <el-select v-model="companyManage.companyType" placeholder="单位类型" @change="getCompanyType">
              <el-option :label="item.name" :value="item.id" v-for='item in companyList' :key='item.id'></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单位归属地">
            <el-cascader size="large" :options="options" v-model="companyManage.selectedOptions" @change="handleChange"></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button type="default" @click="resetSeachConditions">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" class="addBtn" @click="addCompany">新增</el-button>
      </div>
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="companyName" label="单位名称"></el-table-column>
        <el-table-column prop="companyTypeName" label="单位类型">
          <!-- <template slot-scope="scope">
            <span>{{scope.row.companyTypeName}}</span>
          </template> -->
        </el-table-column>
        <el-table-column prop="linkMan" label="联系人"></el-table-column>
        <el-table-column prop="linkMobile" label="联系方式"></el-table-column>
        <el-table-column prop="address" label="单位地址"></el-table-column>
        <el-table-column prop="GPSAddress" label="GPS地址">
          <template slot-scope="scope">
            <span>{{scope.row.lon}}，{{scope.row.lat}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="organizationCode" label="组织机构代码证"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="handleView(scope.row)" type="text" size="small">查看</el-button>
            <!-- <el-button @click="handleView(scope.row)" type="text" size="small">查看</el-button> -->
            <el-button type="text" size="small" @click="editForm(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handlerDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <!-- 操作页 新增修改-->
    <div class="companyAdd" v-if="!isView&&isAdd">
      <el-button type="private" size="small" @click="goBack">返回</el-button>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="单位名称" prop="companyName">
          <el-input v-model="ruleForm.companyName"></el-input>
        </el-form-item>
        <el-form-item label="单位类型" prop="companyType">
          <el-select v-model="ruleForm.companyType" placeholder="单位类型" @change="getCompanyType">
            <el-option :label="item.name" :value="item.id" v-for='item in companyList' :key='item.id'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属监管公司" prop="belongSupervise" v-if="companyManage.companyType==1">
          <!-- <el-input v-model="ruleForm.belongSupervise" placeholder="监管单位"></el-input> -->
          <el-select v-model="ruleForm.belongSupervise" placeholder="所属监管公司">
            <el-option :label="item.companyName" :value="item.id" v-for='item in belongSupervises' :key='item.id'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="linkMan">
          <el-input v-model="ruleForm.linkMan"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="linkMan">
          <el-input v-model="ruleForm.linkMobile"></el-input>
        </el-form-item>
        <el-form-item label="所属市辖区" prop="selectedOptions">
          <el-cascader size="large" :options="options" v-model="ruleForm.selectedOptions" @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="ruleForm.address" @blur='getLocations'></el-input>
        </el-form-item>
        <el-form-item label="GPS地址" prop="GPSLocation">
          <el-input v-model="ruleForm.GPSLocation" disabled>
            <!-- <template slot="append">获取经纬度</template> -->
            <el-button slot="append" icon="el-icon-location-outline"></el-button>
            <!-- <span  slot='append' @click='getLocations'></span> -->
          </el-input>
        </el-form-item>
        <el-form-item label="组织机构代码" prop="organizationCode" class="organizationCode">
          <el-input v-model="ruleForm.organizationCode"></el-input>
        </el-form-item>
        <el-form-item v-if="isAdd">
          <el-button @click="onSubmit('ruleForm')">确定</el-button>
          <el-button @click="cancleUpdate">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 这是查看 -->
    <div class="companyAdd" v-if="!isAdd&&isView">
      <el-button type="private" size="small" @click="goBack">返回</el-button>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="单位名称" prop="companyName">
          <el-input v-model="ruleForm.companyName" disabled></el-input>
        </el-form-item>
        <el-form-item label="单位类型" prop="companyType">
          <el-select v-model="ruleForm.companyType" placeholder="单位类型" disabled @change="getCompanyType">
            <el-option label="产废方" value="1"></el-option>
            <el-option label="处置方" value="2"></el-option>
            <el-option label="运输方" value="3"></el-option>
            <el-option label="运营方" value="4"></el-option>
            <el-option label="监管方" value="5"></el-option>
            <el-option label="管理员" value="6"></el-option>
            <el-option label="处置运营方" value="7"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属监管公司" prop="belongSupervise" v-if="companyManage.companyType==1">
          <!-- <el-input v-model="ruleForm.belongSupervise" placeholder="监管单位"></el-input> -->
          <el-select v-model="ruleForm.belongSupervise" placeholder="所属监管公司" disabled>
            <el-option :label="item.companyName" :value="item.id" v-for='item in belongSupervises' :key='item.id'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="linkMan">
          <el-input v-model="ruleForm.linkMan" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="linkMan">
          <el-input v-model="ruleForm.linkMobile" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属市辖区" prop="selectedOptions">
          <el-cascader size="large" :options="options" v-model="ruleForm.selectedOptions" @change="handleChange" disabled></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="ruleForm.address" disabled></el-input>
        </el-form-item>
        <el-form-item label="GPS地址" prop="GPSLocation">
          <el-input v-model="ruleForm.GPSLocation" disabled>
            <!-- <template slot="append">获取经纬度</template> -->
            <!-- <el-button slot="append" @click='getLocations'></el-button> -->
            <!-- <span icon="el-icon-location-outline" slot='append' @click='getLocations'></span> -->
          </el-input>
        </el-form-item>
        <el-form-item label="组织机构代码" prop="organizationCode" class="organizationCode">
          <el-input v-model="ruleForm.organizationCode" disabled></el-input>
        </el-form-item>
        <el-form-item v-if="isView">
          <!-- <el-button @click="editForm">编辑</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <div id="mask" v-if="showMap">
      <div class="mapContent">
        <div id="amapContainer" style="height:50%;width:50%;">
          <!-- <el-amap id="mapcointainer" :center="center"></el-amap> -->
        </div>
        <el-button @click="sureLocation">确定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import {
  regionDataPlus,
  CodeToText,
  TextToCode
} from "element-china-area-data";


export default {
  name: "CompanyManage",
  inject: ["reload"],
  data() {
    return {
      isView: false,
      companyManage: {
        companyName: "",
        companyType: "",
        selectedOptions: []
      },
      currentPage: 1,
      tableData: [],
      limit: 10,
      page: 1,
      total: 0,
      options: regionDataPlus,
      arr: [],
      map: "",
      isAdd: false,
      ruleForm: {
        companyName: "",
        companyType: null,
        selectedOptions: [],
        linkMan: "",
        linkMobile: "",
        address: "",
        GPSLocation: "",
        organizationCode: "",
        province: "",
        city: "",
        district: "",
        belongSupervise: null,
        log: "",
        lat: "",
        id: ""
      },
      rules: {
        companyName: [
          { required: true, message: "请输入单位名称", triggle: "blur" }
        ],
        companyType: [{
          type: 'number',
          required: true,
          message: "请选择单位类型",
          triggle: "change"
        }],
        linkMan: [{
          required: true,
          message: "请填写联系人",
          triggle: "blur"
        }],
        linkMobile: [{
          required: true,
          message: "请填写联系电话",
          triggle: "blur"
        }],
        selectedOptions: [{
          type: "array",
          required: true,
          message: "请选择市辖区",
          triggle: "change"
        }],
        address: [{
          required: true,
          message: "请填写详细地址",
          triggle: "blur"
        }],
        GPSLocation: [{
          required: true,
          message: "请填写GPS地址",
          triggle: "blur"
        }],
        organizationCode: [{
          required: true,
          message: "请填写组织机构代码",
          triggle: "blur"
        }],
        belongSupervise: [{
          type: 'number',
          required: true,
          message: "请填写所属监管单位",
          triggle: "blur"
        }]
      },
      showMap: false,
      isUpdate: false,
      companyList: [],
      belongSupervises: []
    };
  },
  created() {
    this.initList();

  },
  mounted() {
    // 获取公司类型
    this.$common.$ajax('/sys/company/type/list', {}, 'get').then(res => {
      this.companyList = res.data.body;
    })

    // 获取监管公司
    this.$common.$ajax('/sys/company/list', { companyType: 5, page: 1, limit: 100000 }, 'get').then(res => {
      this.belongSupervises = res.data.body.list;
    })
  },
  methods: {
    initList() {
      this.$common
        .$ajax(
          "/sys/company/list", {
            page: this.page,
            limit: this.limit,
            companyName: this.companyManage.companyName,
            companyType: this.companyManage.companyType,
            province: this.arr[0] || "",
            city: this.arr[1] || "",
            district: this.arr[2] || ""
          },
          "get"
        )
        .then(res => {
          this.tableData = res.data.body.list;
          this.total = res.data.body.totalCount;
        });
    },

    resetForm(e) {},
    handleSizeChange(val) {
      this.limit = val;
      this.initList();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.initList();
    },
    handleChange(value) {
      // this.ruleForm.selectedOptions = value
      this.arr = value.map(item => {
        return CodeToText[item] == "全部" || CodeToText[item] == "" ?
          "" :
          CodeToText[item];
      });
      this.ruleForm.address = '';
      this.ruleForm.GPSLocation = ''
      // this.ruleForm.selectedOptions = this.arr
    },
    getCompanyType(val) {
      console.log(val);
      this.companyManage.companyType = val;
    },
    onSearch() {
      this.initList();
    },
    resetSeachConditions() {
      this.companyManage.companyName = "";
      this.companyManage.companyType = "";
      this.companyManage.selectedOptions = [];
      this.initList();
    },
    addCompany() {
      this.isAdd = true;
    },
    goBack() {
      this.reload();
    },
    // 获取经纬度
    getLocations() {
      var _this = this;
      if (this.ruleForm.address == "") {
        this.$message({
          message: "请输入地址后重试",
          type: "error"
        });
        return;
      } else {
        var geocoder, marker, proviceCityDistrict;
        var map = new AMap.Map("amapContainer", {
          resizeEnable: true
        });
        AMap.plugin('AMap.Geocoder', function() { //异步加载插件
          if (!geocoder) {
            geocoder = new AMap.Geocoder({
              city: "" //城市设为北京，默认：“全国”
            });
          }
          // console.log(CodeToText[_this.ruleForm.selectedOptions])
          console.log(_this.ruleForm.selectedOptions)
          // this.ruleForm.province =CodeToText[this.ruleForm.selectedOptions[0]] || "";
          _this.ruleForm.selectedOptions.forEach(item => {
            proviceCityDistrict += CodeToText[item] || ""
          })
          var detailAddress = proviceCityDistrict + _this.ruleForm.address
          geocoder.getLocation(detailAddress, function(status, result) {
            if (status === "complete" && result.geocodes.length) {
              var lnglat = result.geocodes[0].location;
              console.log(lnglat.lng);
              console.log(lnglat.lat);
              var lng = lnglat.lng;
              var lat = lnglat.lat;
              _this.ruleForm.lon = lng.toFixed(4


              );
              _this.ruleForm.lat = lat.toFixed(4);
              // if (!marker) {
              // marker = new AMap.Marker();
              // map.add(marker);
              // }
              // marker.setPosition(lnglat);
              // map.setFitView(mar${}ker);
              _this.ruleForm.GPSLocation = `${_this.ruleForm.lon},${
              _this.ruleForm.lat
            }`;
            } else {
              alert('暂未获取到地址')
            }
          });
        });

      }
    },
    //公司查看
    handleView(scope) {
      console.log(scope);
      this.isAdd = false;
      this.isView = true;
      this.companyManage.companyType = scope.companyType
      // 赋值
      this.ruleForm.companyName = scope.companyName;
      this.ruleForm.companyType = scope.companyType

      this.ruleForm.linkMan = scope.linkMan;
      this.ruleForm.linkMobile = scope.linkMobile;
      this.ruleForm.belongSupervise = scope.belongSupervise

      let arr = [];
      arr.push(TextToCode[scope.province].code);
      arr.push(TextToCode[scope.province][scope.city].code);
      arr.push(TextToCode[scope.province][scope.city][scope.district].code);
      this.ruleForm.selectedOptions = arr;
      this.ruleForm.address = scope.address;
      console.log(this.ruleForm.selectedOptions);
      this.ruleForm.GPSLocation = `${scope.lon},${scope.lat}`;
      this.ruleForm.organizationCode = scope.organizationCode;
      this.ruleForm.id = scope.id;
      this.$nextTick(() => {
        this.ruleForm.selectedOptions = arr;
      })
    },
    //公司信息编辑

    editForm(scope) {
      console.log(scope)
      this.isView = false;
      this.isUpdate = true;
      this.isAdd = true;
      this.companyManage.companyType = scope.companyType
      this.ruleForm.belongSupervise = scope.belongSupervise
      // 赋值
      this.ruleForm.companyName = scope.companyName;
      this.ruleForm.companyType = scope.companyType;
      this.belongSupervise = scope.belongSupervise
      this.ruleForm.linkMan = scope.linkMan;
      this.ruleForm.linkMobile = scope.linkMobile;
      let arr = [];
      arr.push(TextToCode[scope.province].code);
      arr.push(TextToCode[scope.province][scope.city].code);
      arr.push(TextToCode[scope.province][scope.city][scope.district].code);
      this.ruleForm.selectedOptions = arr;
      this.ruleForm.address = scope.address;
      console.log(this.ruleForm.selectedOptions);
      this.ruleForm.GPSLocation = `${scope.lon},${scope.lat}`;
      this.ruleForm.organizationCode = scope.organizationCode;
      this.ruleForm.id = scope.id;
      this.$nextTick(() => {
        this.ruleForm.selectedOptions = arr;
      })
    },
    // 获取经纬度
    sureLocation() {
      this.showMap = false;
    },
    cancleUpdate() {
      this.reload();
    },
    onSubmit(formName) {
      console.log(this.ruleForm)
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.isUpdate) {
            this.ruleForm.province =
              CodeToText[this.ruleForm.selectedOptions[0]] || "";
            this.ruleForm.city =
              CodeToText[this.ruleForm.selectedOptions[1]] || "";
            this.ruleForm.district =
              CodeToText[this.ruleForm.selectedOptions[2]] || "";
            this.$common
              .$ajax("/sys/company/update", this.ruleForm, "post")
              .then(res => {
                this.$message({
                  message: "修改成功",
                  type: "success"
                });
                this.reload();
              });
          }
          if (!this.isUpdate) {
            // 这是新增
            this.ruleForm.province =
              CodeToText[this.ruleForm.selectedOptions[0]] || "";
            this.ruleForm.city =
              CodeToText[this.ruleForm.selectedOptions[1]] || "";
            this.ruleForm.district =
              CodeToText[this.ruleForm.selectedOptions[2]] || "";
            this.$common
              .$ajax("/sys/company/save", this.ruleForm, "post")
              .then(res => {
                this.$message({
                  message: "新增成功",
                  type: "success"
                });
                this.reload();
              });
          } else {
            console.log("error submit");
            return;
          }
        }
        this.ruleForm.province = this.ruleForm.selectedOptions[0] || "";
        this.ruleForm.city = this.ruleForm.selectedOptions[1] || "";
        this.ruleForm.district = this.ruleForm.selectedOptions[2] || "";
      });
    },
    handlerDelete(item) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          this.$common
            .$ajax("/sys/company/delete", { id: item.id }, "get")
            .then(res => {
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.reload();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};

</script>
<style lang="scss" scoped>
.companyManage {
  .search {
    display: flex;
    justify-content: space-between;

    .addBtn {
      height: 40px;
    }
  }
}

.demo-ruleForm {
  width: 50%;
  margin: 0 auto;
}

#mask {
  height: 100%;
  min-height: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 10;

  .mapContent {
    height: 50%;
    width: 50%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

</style>
